﻿using System;
using System.Linq;
using Loki;
using Loki.Engine;
using Loki.Model;
using Luna.Data;
using Luna.Data.Security;

namespace Luna.Model.Security
{
    public class SecurityService : ApplicationService<LunaModel, LunaDataModel>, ISecurityService
    {
        public SecurityService()
        {
            _Users = CreateContainer<IUser, Guid>(CacheConfiguration.USERS);
        }

        private static readonly string INDEX_LOGIN = ExpressionHelper.Reflect<IUser>.GetProperty(x => x.Login).Name;

        protected ISecurityDataProvider DataProvider
        {
            get { return DataContext.Security; }
        }

        #region ISecurityService Members

        private EntityContainer<IUser, Guid> _Users;

        public IIndexedEnumerable<IUser, Guid> Users
        {
            get { return _Users; }
        }

        public IUser LogonUser(string P_Login, string P_Password)
        {
            IUser L_FoundUser = _Users.GetAllBy(INDEX_LOGIN, P_Login).FirstOrDefault();
            if (L_FoundUser != null && !L_FoundUser.CheckPassword(P_Password))
            {
                return null;
            }
            else
            {
                ApplicationModel.CurrentUser = L_FoundUser;
            }

            return L_FoundUser;
        }

        public void SaveUser(IUser P_User)
        {
            DataProvider.SaveUser(P_User);
            _Users.Register(P_User);
        }

        #endregion

        private const string _ID = "2D88F26F-20B8-4F75-BC19-160226BCB379";

        private const string NAME = "Luna security service";

        public override Guid ID
        {
            get { return new Guid(_ID); }
        }

        public override string Name
        {
            get { return NAME; }
        }
    }
}
